/**
 * 销售统计页面 - 多维度图表、数据对比分析、报表生成
 */
import React, { useState, useEffect, useCallback } from 'react';
import { 
  FileText, 
  FileSpreadsheet, 
  Calendar,
  RefreshCw,
  TrendingUp,
  DollarSign,
  ShoppingCart,
  Clock,
  Package,
  CheckCircle,
  XCircle
} from 'lucide-react';
import { 
  AnimatedLineChart, 
  AnimatedBarChart, 
  AnimatedPieChart,
  DataComparison 
} from '../dashboard/components';
import { OrderDetailModal } from '../dashboard/components/enhanced';
import { dashboardAPI, type SalesTrendItem, type CategorySalesItem, type SalesPieItem, type DataComparisonItem } from '../../utils/api';

// 商品信息类型
interface ProductInfo {
  _id?: string;
  shopname?: string;
  price?: number;
  nums?: number;
  store?: string;
}

// 本地调试开关：需要查看详细日志时改为 true
const DEBUG = false;

// 订单数据类型（与订单管理页面保持一致）
interface OrderData {
  _id: string;
  // studentId: ProductInfo;
  studentId: string | { _id: string; shopname?: string; price?: number };
  quantity: number;
  totalPrice: string | number;
  customerName: string;
  customerPhone: string;
  address: string;
  status: string;
  createdAt: string;
}

// 解析订单价格（支持字符串和数字）- 与数据看板页面保持一致
const parsePrice = (price: string | number): number => {
  if (typeof price === 'number') return price;
  if (typeof price === 'string') {
    const cleanPrice = price.replace(/[¥\s,]/g, '').trim();
    return parseFloat(cleanPrice) || 0;
  }
  return 0;
};

const STATUS_MAP: Record<string | number, string> = {
  0: '待处理',
  1: '已发货',
  2: '已完成',
  3: '已取消',
  4: '已退款',
  待处理: '待处理',
  已发货: '已发货',
  已完成: '已完成',
  已取消: '已取消',
  已退款: '已退款'
};

const normalizeOrderStatus = (status: unknown): string => {
  if (status === null || status === undefined) return '未知状态';
  if (typeof status === 'number' || typeof status === 'string') {
    const mapped = STATUS_MAP[status];
    if (mapped) return mapped;
  }
  return String(status);
};

const SalesStats: React.FC = () => {
  // 日期筛选
  const [dateRange, setDateRange] = useState<'7' | '30' | '90' | 'custom'>('30');
  const [customStartDate, setCustomStartDate] = useState('');
  const [customEndDate, setCustomEndDate] = useState('');
  
  // 数据加载状态
  const [loading, setLoading] = useState(true);
  
  // 销售数据
  const [salesTrendData, setSalesTrendData] = useState<SalesTrendItem[]>([]);
  const [categorySalesData, setCategorySalesData] = useState<CategorySalesItem[]>([]);
  const [salesPieData, setSalesPieData] = useState<SalesPieItem[]>([]);
  const [comparisonData, setComparisonData] = useState<DataComparisonItem[]>([]);
  
  // 订单数据（与订单管理页面关联）
  const [orders, setOrders] = useState<OrderData[]>([]);
  
  // 订单详情模态框状态
  const [showOrderModal, setShowOrderModal] = useState(false);
  const [selectedOrderStatus, setSelectedOrderStatus] = useState<string>('');
  const [orderModalTitle, setOrderModalTitle] = useState<string>('订单明细');
  const [exportLoading, setExportLoading] = useState(false);
  
  // 统计数据
  const [stats, setStats] = useState({
    totalSales: 0,
    totalOrders: 0,
    avgOrderValue: 0,
    growthRate: 0,
    pendingOrders: 0,
    shippedOrders: 0,
    completedOrders: 0,
    cancelledOrders: 0,
    returnRate: 0,
  });
  
  // 根据订单状态筛选订单
  const getFilteredOrdersByStatus = (status: string) => {
    return orders.filter((order: OrderData) => {
      const orderStatus = String(order.status || '').trim();
      return orderStatus === status;
    });
  };
  
  // 将订单数据转换为OrderDetailModal需要的格式
  const convertOrdersToModalFormat = (orderList: OrderData[]) => {
    return orderList.map((order: OrderData) => {
      const productInfo = typeof order.studentId === 'object' && order.studentId !== null 
        ? order.studentId as ProductInfo
        : null;
      return {
        id: order._id,
        product: productInfo?.shopname || '未知商品',
        user: order.customerName || '未知用户',
        region: order.address?.split('市')[0] + '市' || '未知地区',
        amount: parsePrice(order.totalPrice),
        time: order.createdAt,
        status: order.status || '未知状态',
        store: productInfo?.shopname || '未知店铺',
        quantity: order.quantity || 0,
        customerPhone: order.customerPhone || '未知电话',
        address: order.address || '未知地址'
      };
    });
  };
  
  // 处理订单状态卡片点击
  const handleOrderStatusClick = (status: string, title: string) => {
    setSelectedOrderStatus(status);
    setOrderModalTitle(title);
    setShowOrderModal(true);
  };
  
  // 从订单管理后端获取订单数据（与数据看板页面使用相同的API端点）
  const fetchOrders = useCallback(async (days?: number) => {
    try {
      const ordersRes = await fetch('http://localhost:3000/hsl/order/list', {
        cache: 'no-cache',
        headers: {
          'Cache-Control': 'no-cache',
          'Pragma': 'no-cache'
        }
      });
      const ordersData = await ordersRes.json();
      
      if (ordersData.code === 200 && Array.isArray(ordersData.data)) {
        let filteredOrders: OrderData[] = ordersData.data || [];
        
        // 如果指定了天数，按日期筛选
        if (days) {
          const now = new Date();
          const startDate = new Date(now.getTime() - days * 24 * 60 * 60 * 1000);
          startDate.setHours(0, 0, 0, 0);
          
          filteredOrders = filteredOrders.filter((order: OrderData) => {
            try {
              if (!order.createdAt) return true;
              const orderDate = new Date(order.createdAt);
              if (isNaN(orderDate.getTime())) return true;
              return orderDate >= startDate;
            } catch {
              return true;
            }
          });
        }
        
        const processedOrders = filteredOrders.map((order: OrderData) => ({
          ...order,
          status: normalizeOrderStatus(order.status)
        }));
        setOrders(processedOrders);
        if (DEBUG) {
          console.log('[销售统计] 成功获取订单数据:', processedOrders.length, '条');
        }
        
        // 计算订单状态统计
        const pendingOrders = processedOrders.filter((o: OrderData) => o.status === '待处理').length;
        const shippedOrders = processedOrders.filter((o: OrderData) => o.status === '已发货').length;
        const completedOrders = processedOrders.filter((o: OrderData) => o.status === '已完成').length;
        const cancelledOrders = processedOrders.filter((o: OrderData) => o.status === '已取消').length;
        
        // 返回订单数据和统计信息
        return {
          orders: processedOrders, // 返回已处理的订单数据
          pendingOrders,
          shippedOrders,
          completedOrders,
          cancelledOrders
        };
      }
      setOrders([]);
      return { orders: [], pendingOrders: 0, shippedOrders: 0, completedOrders: 0, cancelledOrders: 0 };
    } catch (error) {
      if (DEBUG) {
        console.error('[销售统计] 获取订单数据失败:', error);
      }
      setOrders([]);
      return { orders: [], pendingOrders: 0, shippedOrders: 0, completedOrders: 0, cancelledOrders: 0 };
    }
  }, []);

  // 获取销售数据（与订单管理后端关联）
  const fetchSalesData = useCallback(async () => {
    const days = dateRange === 'custom' ? undefined : parseInt(dateRange);
    
    try {
      setLoading(true);
      
      // 先获取订单管理数据（这是主要数据源）
      const orderResult = await fetchOrders(days);
      const { orders: fetchedOrders, ...orderStats } = orderResult;
      
      if (DEBUG) {
        console.log('[销售统计] 获取到的订单数量:', fetchedOrders?.length || 0);
        console.log('[销售统计] 订单数据示例:', fetchedOrders?.slice(0, 2));
      }
      
      // 检查订单数据是否为空
      if (!fetchedOrders || fetchedOrders.length === 0) {
        if (DEBUG) {
          console.warn('[销售统计] 警告：没有获取到订单数据，请检查：');
          console.warn('1. 订单管理后端是否正常运行 (http://localhost:3000/hsl/order/list)');
          console.warn('2. 订单管理中是否有订单数据');
          console.warn('3. 日期筛选条件是否过于严格');
        }
      }
      
      // 优化：不等待API数据，直接使用订单数据计算（更快）
      // API数据作为备用，异步获取，不阻塞页面显示
      const apiPromises = Promise.allSettled([
        dashboardAPI.getSalesTrend(days).catch(() => ({ data: null })),
        dashboardAPI.getCategorySales(days).catch(() => ({ data: null })),
        dashboardAPI.getSalesPie(days).catch(() => ({ data: null })),
        dashboardAPI.getComparison(days).catch(() => ({ data: null }))
      ]).then((results) => {
        // 静默处理API结果，不影响主流程
        if (DEBUG) {
          console.log('[销售统计] API数据已获取（备用）');
        }
        return results;
      }).catch(() => {
        // 静默失败
        return [];
      });
      
      // 不等待API，直接继续处理订单数据
      // API数据作为备用，不影响主流程
      if (DEBUG) {
        console.log('[销售统计] 开始处理订单数据，API数据异步加载中...');
      }

      // 优先使用订单管理数据计算（确保与订单管理页面一致）
      // 注意：这里使用所有订单（包括已取消），与订单管理页面保持一致
      // 直接使用 fetchOrders 返回的数据，而不是依赖 orders 状态（避免异步更新问题）
      const allOrdersForCalculation = fetchedOrders || []; // 使用所有订单，不排除已取消
      
      // 优化：使用单次遍历同时计算趋势和类别数据，提高性能
      const trendMap = new Map<string, { sales: number; orders: number }>();
      const categoryMap = new Map<string, { sales: number; orders: number }>();
      let totalSales = 0;
      
      // 单次遍历处理所有订单（使用与数据看板页面相同的parsePrice函数）
      for (const order of allOrdersForCalculation) {
        try {
          // 计算价格（使用统一的parsePrice函数，与数据看板页面保持一致）
          const price = parsePrice(order.totalPrice);
          
          totalSales += price;
          
          // 处理趋势数据
          if (order.createdAt) {
            const orderDate = new Date(order.createdAt);
            if (!isNaN(orderDate.getTime())) {
              const dateKey = orderDate.toISOString().split('T')[0];
              if (!trendMap.has(dateKey)) {
                trendMap.set(dateKey, { sales: 0, orders: 0 });
              }
              const dayData = trendMap.get(dateKey)!;
              dayData.sales += price;
              dayData.orders += 1;
            }
          }
          
          // 处理类别数据（与数据看板页面保持一致）
          const productInfo =
            typeof order.studentId === 'object' && order.studentId !== null
              ? (order.studentId as ProductInfo)
              : undefined;
          const categoryName = productInfo?.shopname || '未分类';
          if (!categoryMap.has(categoryName)) {
            categoryMap.set(categoryName, { sales: 0, orders: 0 });
          }
          const categoryData = categoryMap.get(categoryName)!;
          categoryData.sales += price;
          categoryData.orders += 1;
        } catch {
          // 静默忽略错误订单
        }
      }
      
      // 生成趋势数据
      const calculatedTrend = Array.from(trendMap.entries())
        .map(([date, data]) => ({ 
          date, 
          sales: Math.round(data.sales), 
          orders: data.orders 
        }))
        .sort((a, b) => a.date.localeCompare(b.date));
      
      if (DEBUG) {
        console.log('[销售统计] 从订单管理数据计算销售趋势:', {
          订单总数: allOrdersForCalculation.length,
          趋势数据点: calculatedTrend.length,
          趋势数据示例: calculatedTrend.slice(0, 3)
        });
      }
      
      // 设置销售趋势数据（优先使用订单管理数据）
      setSalesTrendData(calculatedTrend);
      if (DEBUG) {
        console.log('[销售统计] 已设置销售趋势数据:', calculatedTrend.length, '条');
        console.log('[销售统计] 销售趋势数据示例:', calculatedTrend.slice(0, 3));
      }
      
      // 统计数据（已在上面循环中计算 totalSales）
      const totalSalesFromOrders = totalSales;
      const totalOrdersFromOrders = allOrdersForCalculation.length;
      const avgOrderValueFromOrders = totalOrdersFromOrders > 0 
        ? Math.round(totalSalesFromOrders / totalOrdersFromOrders) 
        : 0;
      const returnRate = totalOrdersFromOrders > 0
        ? (orderStats.cancelledOrders / totalOrdersFromOrders) * 100
        : 0;
        
        // 计算增长率（与上期对比）
      const currentPeriod = calculatedTrend.slice(-7).reduce((sum: number, item) => sum + (item.sales || 0), 0);
      const previousPeriod = calculatedTrend.slice(-14, -7).reduce((sum: number, item) => sum + (item.sales || 0), 0);
        const growthRate = previousPeriod > 0 ? ((currentPeriod - previousPeriod) / previousPeriod) * 100 : 0;
      
      if (DEBUG) {
        console.log('[销售统计] 统计数据:', {
          总销售额: totalSalesFromOrders,
          总订单数: totalOrdersFromOrders,
          客单价: avgOrderValueFromOrders,
          增长率: growthRate,
          退货率: returnRate,
        });
      }
        
        setStats({
        totalSales: totalSalesFromOrders,
        totalOrders: totalOrdersFromOrders,
        avgOrderValue: avgOrderValueFromOrders,
        growthRate,
        returnRate,
        ...orderStats
      });
      
      // 类别数据已在上面循环中计算，直接使用，只展示销售额Top10
      const finalCategoryData = Array.from(categoryMap.entries())
        .map(([name, data]) => ({ 
          name, 
          sales: Math.round(data.sales), 
          orders: data.orders
        }))
        .sort((a, b) => b.sales - a.sales)
        .slice(0, 10);
      
      setCategorySalesData(finalCategoryData);
      if (DEBUG) {
        console.log('[销售统计] 从订单管理数据计算类别销售:', {
          类别数量: finalCategoryData.length,
          类别数据示例: finalCategoryData.slice(0, 3)
        });
        console.log('[销售统计] 已设置类别销售数据:', finalCategoryData.length, '条');
        console.log('[销售统计] 统计数据:', {
          总销售额: totalSalesFromOrders,
          总订单数: totalOrdersFromOrders,
          客单价: avgOrderValueFromOrders,
          增长率: growthRate,
          待处理: orderStats.pendingOrders,
          已发货: orderStats.shippedOrders,
          已完成: orderStats.completedOrders,
          已取消: orderStats.cancelledOrders
        });
      }
      
      // 处理饼图数据（使用刚计算的类别数据，确保与订单管理页面一致）
      if (finalCategoryData.length > 0) {
        const pieData = finalCategoryData.map((item, index) => {
          const colors = ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#ec4899', '#06b6d4'];
          return {
            name: item.name,
            value: item.sales,
            color: colors[index % colors.length]
          };
        });
        setSalesPieData(pieData);
        if (DEBUG) {
          console.log('[销售统计] 从订单管理数据生成饼图数据:', pieData.length, '条');
          console.log('[销售统计] 已设置饼图数据:', pieData.length, '条');
        }
      } else {
        if (DEBUG) {
          console.warn('[销售统计] 没有类别数据，无法生成饼图');
        }
        setSalesPieData([]);
      }
      
      // 异步获取对比数据（不阻塞主流程）
      apiPromises.then((results) => {
        if (results[3]?.status === 'fulfilled' && results[3].value?.data) {
          setComparisonData(results[3].value.data);
        }
      });
    } catch (error: unknown) {
      console.error('[销售统计] 获取销售数据失败:', error);
      const errorMessage = error && typeof error === 'object' && 'response' in error 
        ? (error as { response?: { data?: unknown } }).response?.data 
        : error instanceof Error ? error.message : '未知错误';
      console.error('[销售统计] 错误详情:', errorMessage);
      
      // 即使API失败，也尝试从订单数据计算（使用所有订单，与订单管理页面一致）
      try {
        const orderResult = await fetchOrders(days);
        const { orders: fetchedOrders, ...orderStats } = orderResult;
        const allOrdersForCalculation = fetchedOrders || []; // 使用所有订单，不排除已取消
        
        const totalSalesFromOrders = allOrdersForCalculation.reduce((sum: number, order: OrderData) => {
          const price = parsePrice(order.totalPrice);
          return sum + price;
        }, 0);
        const totalOrdersFromOrders = allOrdersForCalculation.length;
        const avgOrderValueFromOrders = totalOrdersFromOrders > 0 
          ? Math.round(totalSalesFromOrders / totalOrdersFromOrders) 
          : 0;
        const returnRate = totalOrdersFromOrders > 0
          ? (orderStats.cancelledOrders / totalOrdersFromOrders) * 100
          : 0;
        
        // 从订单数据计算图表数据
        const trendMap = new Map<string, { sales: number; orders: number }>();
        allOrdersForCalculation.forEach((order: OrderData) => {
          try {
            if (!order.createdAt) return;
            const orderDate = new Date(order.createdAt);
            if (isNaN(orderDate.getTime())) return;
            const dateKey = orderDate.toISOString().split('T')[0];
            const price = parsePrice(order.totalPrice);
            if (!trendMap.has(dateKey)) {
              trendMap.set(dateKey, { sales: 0, orders: 0 });
            }
            const dayData = trendMap.get(dateKey)!;
            dayData.sales += price;
            dayData.orders += 1;
          } catch (e) {
            if (DEBUG) {
              console.warn('[销售统计] 处理订单日期失败:', order._id, e);
            }
          }
        });
        const calculatedTrend = Array.from(trendMap.entries())
          .map(([date, data]) => ({ date, sales: Math.round(data.sales), orders: data.orders }))
          .sort((a, b) => a.date.localeCompare(b.date));
        
        // 计算类别销售
        const categoryMap = new Map<string, { sales: number; orders: number }>();
        allOrdersForCalculation.forEach((order: OrderData) => {
          try {
            // 与数据看板页面保持一致
            const productInfo =
              typeof order.studentId === 'object' && order.studentId !== null
                ? (order.studentId as ProductInfo)
                : undefined;
            const categoryName = productInfo?.shopname || '未分类';
            const price = parsePrice(order.totalPrice);
            if (!categoryMap.has(categoryName)) {
              categoryMap.set(categoryName, { sales: 0, orders: 0 });
            }
            const categoryData = categoryMap.get(categoryName)!;
            categoryData.sales += price;
            categoryData.orders += 1;
          } catch {
            // 忽略
          }
        });
        const calculatedCategory = Array.from(categoryMap.entries())
          .map(([name, data]) => ({ name, sales: Math.round(data.sales), orders: data.orders }))
          .sort((a, b) => b.sales - a.sales);
        
        // 生成饼图数据
        const pieData = calculatedCategory.map((item, index) => {
          const colors = ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#ec4899', '#06b6d4'];
          return {
            name: item.name,
            value: item.sales,
            color: colors[index % colors.length]
          };
        });
        
        // 更新所有数据
        setSalesTrendData(calculatedTrend);
        setCategorySalesData(calculatedCategory);
        setSalesPieData(pieData);
        if (DEBUG) {
          console.log('[销售统计] 错误恢复：已设置饼图数据:', pieData.length, '条', pieData);
        }
        setStats({
          totalSales: totalSalesFromOrders,
          totalOrders: totalOrdersFromOrders,
          avgOrderValue: avgOrderValueFromOrders,
          growthRate: 0,
          returnRate,
          ...orderStats
        });
        
        if (DEBUG) {
          console.log('[销售统计] 已从订单管理数据恢复，显示数据');
        }
      } catch (fallbackError) {
        console.error('[销售统计] 从订单数据恢复也失败:', fallbackError);
        // 只有在所有方法都失败时才显示错误
        // 不显示alert，让页面继续加载，至少显示空状态
      }
    } finally {
      setLoading(false);
    }
    
     
  }, [dateRange, fetchOrders]);

  useEffect(() => {
    fetchSalesData();
  }, [fetchSalesData]);

  // 导出报表
  const exportReport = async (format: 'pdf' | 'excel') => {
    try {
      // 检查数据是否已加载
      if (loading) {
        alert('数据正在加载中，请稍候再试');
        return;
      }

      // 检查是否有数据
      if (stats.totalOrders === 0 && categorySalesData.length === 0 && salesTrendData.length === 0) {
        alert('暂无数据可导出，请先加载数据');
        return;
      }

      // 格式化日期范围
      const formatDateRange = () => {
        if (dateRange === 'custom') {
          if (customStartDate && customEndDate) {
            return `${customStartDate} 至 ${customEndDate}`;
          } else if (customStartDate) {
            return `${customStartDate} 起`;
          } else if (customEndDate) {
            return `至 ${customEndDate}`;
          } else {
            return '自定义日期';
          }
        }
        return `最近${dateRange}天`;
      };

      // CSV转义函数（处理包含逗号、引号等特殊字符的字段）
      const escapeCsvField = (field: string | number): string => {
        const str = String(field);
        // 如果包含逗号、引号或换行符，需要用引号包裹，并转义内部引号
        if (str.includes(',') || str.includes('"') || str.includes('\n')) {
          return `"${str.replace(/"/g, '""')}"`;
        }
        return str;
      };

      if (format === 'pdf') {
        // 生成PDF报表
        const printWindow = window.open('', '_blank');
        if (!printWindow) {
          alert('无法打开打印窗口，请检查浏览器弹窗设置');
          return;
        }

        try {
          printWindow.document.write(`
            <html>
              <head>
                <title>销售统计报表</title>
                <meta charset="UTF-8">
                <style>
                  body { font-family: "Microsoft YaHei", Arial, sans-serif; padding: 20px; }
                  h1 { color: #333; margin-bottom: 10px; }
                  h2 { color: #555; margin-top: 30px; margin-bottom: 15px; }
                  p { color: #666; margin: 10px 0; }
                  table { width: 100%; border-collapse: collapse; margin: 20px 0; }
                  th, td { border: 1px solid #ddd; padding: 10px; text-align: left; }
                  th { background-color: #f2f2f2; font-weight: bold; }
                  tr:nth-child(even) { background-color: #f9f9f9; }
                  .no-data { text-align: center; color: #999; padding: 20px; }
                </style>
              </head>
              <body>
                <h1>销售统计报表</h1>
                <p><strong>统计周期:</strong> ${formatDateRange()}</p>
                <p><strong>生成时间:</strong> ${new Date().toLocaleString('zh-CN')}</p>
                
                <h2>销售概览</h2>
                <table>
                  <tr><th>指标</th><th>数值</th></tr>
                  <tr><td>总销售额</td><td>¥${stats.totalSales.toLocaleString()}</td></tr>
                  <tr><td>总订单数</td><td>${stats.totalOrders.toLocaleString()}</td></tr>
                  <tr><td>区间客单价</td><td>¥${stats.avgOrderValue.toFixed(2)}</td></tr>
                  <tr><td>增长率</td><td>${stats.growthRate.toFixed(2)}%</td></tr>
                  <tr><td>退货率</td><td>${stats.returnRate.toFixed(2)}%</td></tr>
                </table>
                
                <h2>类别销售统计</h2>
                <table>
                  <tr><th>类别</th><th>销售额</th><th>订单数</th></tr>
                  ${categorySalesData.length > 0 
                    ? categorySalesData.map(item => `
                    <tr>
                        <td>${String(item.name).replace(/</g, '&lt;').replace(/>/g, '&gt;')}</td>
                      <td>¥${item.sales.toLocaleString()}</td>
                      <td>${item.orders.toLocaleString()}</td>
                    </tr>
                    `).join('')
                    : '<tr><td colspan="3" class="no-data">暂无类别销售数据</td></tr>'
                  }
                </table>
                
                <h2>销售趋势数据</h2>
                <table>
                  <tr><th>日期</th><th>销售额</th><th>订单数</th><th>客单价</th></tr>
                  ${salesTrendData.length > 0
                    ? salesTrendData.map(item => {
                        const avgValue = item.orders > 0 ? (item.sales / item.orders).toFixed(2) : '0.00';
                        return `
                          <tr>
                            <td>${item.date}</td>
                            <td>¥${item.sales.toLocaleString()}</td>
                            <td>${item.orders.toLocaleString()}</td>
                            <td>¥${avgValue}</td>
                          </tr>
                        `;
                      }).join('')
                    : '<tr><td colspan="4" class="no-data">暂无销售趋势数据</td></tr>'
                  }
                </table>
              </body>
            </html>
          `);
          printWindow.document.close();
          
          // 等待内容加载完成后再打印
          setTimeout(() => {
            try {
            printWindow.print();
            } catch (printError) {
              console.error('打印失败:', printError);
              alert('打印失败，请手动使用浏览器的打印功能');
            }
          }, 500);
        } catch (writeError) {
          console.error('写入打印窗口失败:', writeError);
          printWindow.close();
          alert('生成PDF报表失败，请重试');
        }
      } else if (format === 'excel') {
        // 生成Excel报表（CSV格式）
        try {
          const csvRows: string[] = [];
          
          // 添加BOM以支持中文
          csvRows.push('\ufeff');
          
          // 标题和日期范围
          csvRows.push(escapeCsvField('销售统计报表'));
          csvRows.push([escapeCsvField('统计周期'), escapeCsvField(formatDateRange())].join(','));
          csvRows.push([escapeCsvField('生成时间'), escapeCsvField(new Date().toLocaleString('zh-CN'))].join(','));
          csvRows.push('');
          
          // 销售概览
          csvRows.push(escapeCsvField('销售概览'));
          csvRows.push([escapeCsvField('指标'), escapeCsvField('数值')].join(','));
          csvRows.push([escapeCsvField('总销售额'), escapeCsvField(`¥${stats.totalSales.toLocaleString()}`)].join(','));
          csvRows.push([escapeCsvField('总订单数'), escapeCsvField(stats.totalOrders.toLocaleString())].join(','));
          csvRows.push([escapeCsvField('区间客单价'), escapeCsvField(`¥${stats.avgOrderValue.toFixed(2)}`)].join(','));
          csvRows.push([escapeCsvField('增长率'), escapeCsvField(`${stats.growthRate.toFixed(2)}%`)].join(','));
          csvRows.push([escapeCsvField('退货率'), escapeCsvField(`${stats.returnRate.toFixed(2)}%`)].join(','));
          csvRows.push('');
          
          // 类别销售统计
          csvRows.push(escapeCsvField('类别销售统计'));
          csvRows.push([escapeCsvField('类别'), escapeCsvField('销售额'), escapeCsvField('订单数')].join(','));
          if (categorySalesData.length > 0) {
            categorySalesData.forEach(item => {
              csvRows.push([
                escapeCsvField(item.name),
                escapeCsvField(`¥${item.sales.toLocaleString()}`),
                escapeCsvField(item.orders.toLocaleString())
              ].join(','));
            });
          } else {
            csvRows.push([escapeCsvField('暂无类别销售数据'), '', ''].join(','));
          }
          csvRows.push('');
          
          // 销售趋势数据
          csvRows.push(escapeCsvField('销售趋势数据'));
          csvRows.push([escapeCsvField('日期'), escapeCsvField('销售额'), escapeCsvField('订单数'), escapeCsvField('客单价')].join(','));
          if (salesTrendData.length > 0) {
            salesTrendData.forEach(item => {
              const avgValue = item.orders > 0 ? (item.sales / item.orders).toFixed(2) : '0.00';
              csvRows.push([
                escapeCsvField(item.date),
                escapeCsvField(`¥${item.sales.toLocaleString()}`),
                escapeCsvField(item.orders.toLocaleString()),
                escapeCsvField(`¥${avgValue}`)
              ].join(','));
            });
          } else {
            csvRows.push([escapeCsvField('暂无销售趋势数据'), '', '', ''].join(','));
          }

          const csvContent = csvRows.join('\n');
          const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        const url = URL.createObjectURL(blob);
          
        link.setAttribute('href', url);
        link.setAttribute('download', `销售统计报表_${new Date().toISOString().split('T')[0]}.csv`);
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
          
          try {
        link.click();
            // 清理URL对象
            setTimeout(() => {
              URL.revokeObjectURL(url);
              document.body.removeChild(link);
            }, 100);
          } catch (clickError) {
            console.error('触发下载失败:', clickError);
            URL.revokeObjectURL(url);
        document.body.removeChild(link);
            alert('下载失败，请检查浏览器设置或手动保存文件');
          }
        } catch (csvError) {
          console.error('生成CSV失败:', csvError);
          alert('生成Excel报表失败，请重试');
        }
      }
    } catch (error) {
      console.error('导出报表失败:', error);
      const errorMessage = error instanceof Error ? error.message : '未知错误';
      alert(`导出报表失败: ${errorMessage}，请稍后重试`);
    } finally {
      setExportLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-gray-500">加载中...</div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* 页面标题和操作栏 */}
      <div className="flex items-center justify-between">
    <div>
        <h2 className="text-2xl font-bold text-gray-800">销售统计</h2>
        <p className="text-gray-500 mt-1">销售数据分析与统计</p>
      </div>
      
        {/* 报表导出按钮 */}
        <div className="flex items-center gap-3">
          <button
            onClick={() => exportReport('pdf')}
            disabled={exportLoading}
            className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-colors ${
              exportLoading
                ? 'bg-red-400 text-white cursor-not-allowed'
                : 'bg-red-500 text-white hover:bg-red-600'
            }`}
          >
            <FileText size={18} />
            {exportLoading ? '导出中...' : '导出PDF'}
          </button>
          <button
            onClick={() => exportReport('excel')}
            disabled={exportLoading}
            className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-colors ${
              exportLoading
                ? 'bg-green-400 text-white cursor-not-allowed'
                : 'bg-green-500 text-white hover:bg-green-600'
            }`}
          >
            <FileSpreadsheet size={18} />
            {exportLoading ? '导出中...' : '导出Excel'}
          </button>
          <button
            onClick={fetchSalesData}
            disabled={loading}
            className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-colors ${
              loading
                ? 'bg-blue-400 text-white cursor-not-allowed'
                : 'bg-blue-500 text-white hover:bg-blue-600'
            }`}
          >
            <RefreshCw size={18} />
            {loading ? '刷新中...' : '刷新'}
          </button>
        </div>
      </div>

      {/* 日期筛选 */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-100 p-4">
        <div className="flex items-center gap-4">
          <div className="flex items-center gap-2">
            <Calendar size={18} className="text-gray-500" />
            <span className="text-sm font-medium text-gray-700">统计周期：</span>
          </div>
          <div className="flex items-center gap-2">
            {(['7', '30', '90'] as const).map((days) => (
              <button
                key={days}
                onClick={() => setDateRange(days)}
                className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
                  dateRange === days
                    ? 'bg-blue-500 text-white'
                    : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                }`}
              >
                最近{days}天
              </button>
            ))}
            <button
              onClick={() => setDateRange('custom')}
              className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
                dateRange === 'custom'
                  ? 'bg-blue-500 text-white'
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
              }`}
            >
              自定义
            </button>
          </div>
          {dateRange === 'custom' && (
            <div className="flex items-center gap-2">
              <input
                type="date"
                value={customStartDate}
                onChange={(e) => setCustomStartDate(e.target.value)}
                className="px-3 py-2 border border-gray-300 rounded-lg text-sm"
              />
              <span className="text-gray-500">至</span>
              <input
                type="date"
                value={customEndDate}
                onChange={(e) => setCustomEndDate(e.target.value)}
                className="px-3 py-2 border border-gray-300 rounded-lg text-sm"
              />
            </div>
          )}
        </div>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <div className="bg-white rounded-lg shadow-sm border border-gray-100 p-6">
          <div className="flex items-center justify-between mb-4">
            <div className="p-3 bg-blue-100 rounded-lg">
              <DollarSign size={24} className="text-blue-600" />
            </div>
            <div className={`flex items-center gap-1 text-sm font-semibold ${
              stats.growthRate >= 0 ? 'text-green-600' : 'text-red-600'
            }`}>
              <TrendingUp size={16} />
              {stats.growthRate >= 0 ? '+' : ''}{stats.growthRate.toFixed(2)}%
            </div>
          </div>
          <div className="text-sm text-gray-500 mb-1">总销售额</div>
          <div className="text-2xl font-bold text-gray-800">
            ¥{stats.totalSales.toLocaleString()}
          </div>
        </div>

        <div className="bg-white rounded-lg shadow-sm border border-gray-100 p-6">
          <div className="flex items-center justify-between mb-4">
            <div className="p-3 bg-green-100 rounded-lg">
              <ShoppingCart size={24} className="text-green-600" />
            </div>
          </div>
          <div className="text-sm text-gray-500 mb-1">总订单数</div>
          <div className="text-2xl font-bold text-gray-800">
            {stats.totalOrders.toLocaleString()}
          </div>
        </div>

        <div className="bg-white rounded-lg shadow-sm border border-gray-100 p-6">
          <div className="flex items-center justify-between mb-4">
            <div className="p-3 bg-purple-100 rounded-lg">
              <DollarSign size={24} className="text-purple-600" />
            </div>
          </div>
          <div className="text-sm text-gray-500 mb-1">区间客单价</div>
          <div className="text-2xl font-bold text-gray-800">
            ¥{stats.avgOrderValue.toFixed(2)}
          </div>
        </div>

        <div className="bg-white rounded-lg shadow-sm border border-gray-100 p-6">
          <div className="flex items-center justify-between mb-4">
            <div className="p-3 bg-orange-100 rounded-lg">
              <TrendingUp size={24} className="text-orange-600" />
            </div>
          </div>
          <div className="text-sm text-gray-500 mb-1">增长率</div>
          <div className={`text-2xl font-bold ${
            stats.growthRate >= 0 ? 'text-green-600' : 'text-red-600'
          }`}>
            {stats.growthRate >= 0 ? '+' : ''}{stats.growthRate.toFixed(2)}%
          </div>
          <div className="mt-1 text-xs text-gray-500">
            退货率：{stats.returnRate.toFixed(2)}%
          </div>
        </div>
      </div>

      {/* 订单状态统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <div 
          className="bg-white rounded-lg shadow-sm border border-gray-100 p-6 cursor-pointer hover:shadow-md hover:border-yellow-300 transition-all"
          onClick={() => handleOrderStatusClick('待处理', '待处理订单明细')}
        >
          <div className="flex items-center justify-between mb-4">
            <div className="p-3 bg-yellow-100 rounded-lg">
              <Clock size={24} className="text-yellow-600" />
            </div>
          </div>
          <div className="text-sm text-gray-500 mb-1">待处理订单</div>
          <div className="text-2xl font-bold text-gray-800">
            {stats.pendingOrders.toLocaleString()}
          </div>
          {stats.pendingOrders > 0 && (
            <div className="text-xs text-gray-400 mt-2">点击查看详情</div>
          )}
        </div>

        <div 
          className="bg-white rounded-lg shadow-sm border border-gray-100 p-6 cursor-pointer hover:shadow-md hover:border-blue-300 transition-all"
          onClick={() => handleOrderStatusClick('已发货', '已发货订单明细')}
        >
          <div className="flex items-center justify-between mb-4">
            <div className="p-3 bg-blue-100 rounded-lg">
              <Package size={24} className="text-blue-600" />
            </div>
          </div>
          <div className="text-sm text-gray-500 mb-1">已发货订单</div>
          <div className="text-2xl font-bold text-gray-800">
            {stats.shippedOrders.toLocaleString()}
          </div>
          {stats.shippedOrders > 0 && (
            <div className="text-xs text-gray-400 mt-2">点击查看详情</div>
          )}
        </div>

        <div 
          className="bg-white rounded-lg shadow-sm border border-gray-100 p-6 cursor-pointer hover:shadow-md hover:border-green-300 transition-all"
          onClick={() => handleOrderStatusClick('已完成', '已完成订单明细')}
        >
          <div className="flex items-center justify-between mb-4">
            <div className="p-3 bg-green-100 rounded-lg">
              <CheckCircle size={24} className="text-green-600" />
            </div>
          </div>
          <div className="text-sm text-gray-500 mb-1">已完成订单</div>
          <div className="text-2xl font-bold text-gray-800">
            {stats.completedOrders.toLocaleString()}
          </div>
          {stats.completedOrders > 0 && (
            <div className="text-xs text-gray-400 mt-2">点击查看详情</div>
          )}
        </div>

        <div 
          className="bg-white rounded-lg shadow-sm border border-gray-100 p-6 cursor-pointer hover:shadow-md hover:border-red-300 transition-all"
          onClick={() => handleOrderStatusClick('已取消', '已取消订单明细')}
        >
          <div className="flex items-center justify-between mb-4">
            <div className="p-3 bg-red-100 rounded-lg">
              <XCircle size={24} className="text-red-600" />
            </div>
          </div>
          <div className="text-sm text-gray-500 mb-1">已取消订单</div>
          <div className="text-2xl font-bold text-gray-800">
            {stats.cancelledOrders.toLocaleString()}
          </div>
          {stats.cancelledOrders > 0 && (
            <div className="text-xs text-gray-400 mt-2">点击查看详情</div>
          )}
        </div>
      </div>

      {/* 多维度图表区域 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 销售趋势折线图 */}
        <div className="bg-white rounded-lg shadow-sm border border-gray-100 p-6">
          <div className="mb-6">
            <h3 className="text-lg font-bold text-gray-800 mb-1">销售趋势分析</h3>
            <p className="text-xs text-gray-500">销售额与订单数趋势变化</p>
          </div>
          {salesTrendData.length > 0 ? (
            <AnimatedLineChart
              data={salesTrendData}
              lines={[
                { dataKey: 'sales', name: '销售额(元)', color: '#3b82f6', strokeWidth: 2 },
                { dataKey: 'orders', name: '订单数(单)', color: '#10b981', strokeWidth: 2 },
              ]}
              height={300}
              showAnimation={true}
            />
          ) : (
            <div className="flex items-center justify-center h-[300px] text-gray-400">
              <div className="text-center">
                <p className="text-sm">暂无数据</p>
                <p className="text-xs mt-2">请确保订单管理中有订单数据</p>
              </div>
            </div>
          )}
        </div>

        {/* 类别销售柱状图 */}
        <div className="bg-white rounded-lg shadow-sm border border-gray-100 p-6">
          <div className="mb-6">
            <h3 className="text-lg font-bold text-gray-800 mb-1">类别销售对比</h3>
            <p className="text-xs text-gray-500">销售额 Top10 品类的销售额与订单数对比</p>
          </div>
          {categorySalesData.length > 0 ? (
            <AnimatedBarChart
              data={categorySalesData}
              bars={[
                { dataKey: 'sales', name: '销售额(元)', color: '#3b82f6' },
                { dataKey: 'orders', name: '订单数(单)', color: '#10b981' },
              ]}
              height={300}
              showAnimation={true}
            />
          ) : (
            <div className="flex items-center justify-center h-[300px] text-gray-400">
              <div className="text-center">
                <p className="text-sm">暂无数据</p>
                <p className="text-xs mt-2">请确保订单管理中有订单数据</p>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* 销售占比饼图和订单状态分布 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 销售占比饼图 */}
        <div className="bg-white rounded-lg shadow-sm border border-gray-100 p-6">
          <div className="mb-6">
            <h3 className="text-lg font-bold text-gray-800 mb-1">销售占比分析</h3>
            <p className="text-xs text-gray-500">各商品类别销售占比分布</p>
          </div>
          {salesPieData.length > 0 ? (
            <AnimatedPieChart
              data={salesPieData}
              height={300}
              showAnimation={true}
              innerRadius={60}
              outerRadius={100}
            />
          ) : (
            <div className="flex items-center justify-center h-[300px] text-gray-400">
              <div className="text-center">
                <p className="text-sm">暂无数据</p>
                <p className="text-xs mt-2">请确保订单管理中有订单数据</p>
              </div>
            </div>
          )}
        </div>

        {/* 订单状态分布 */}
        <div className="bg-white rounded-lg shadow-sm border border-gray-100 p-6">
          <div className="mb-6">
            <h3 className="text-lg font-bold text-gray-800 mb-1">订单状态分布</h3>
            <p className="text-xs text-gray-500">各订单状态的分布情况</p>
          </div>
          {stats.totalOrders > 0 ? (
            <AnimatedPieChart
              data={[
                {
                  name: '待处理',
                  value: stats.pendingOrders,
                  color: '#fbbf24'
                },
                {
                  name: '已发货',
                  value: stats.shippedOrders,
                  color: '#3b82f6'
                },
                {
                  name: '已完成',
                  value: stats.completedOrders,
                  color: '#10b981'
                },
                {
                  name: '已取消',
                  value: stats.cancelledOrders,
                  color: '#ef4444'
                }
              ].filter(item => item.value > 0)}
              height={300}
              showAnimation={true}
              innerRadius={60}
              outerRadius={100}
            />
          ) : (
            <div className="flex items-center justify-center h-[300px] text-gray-400">
              <div className="text-center">
                <p className="text-sm">暂无订单数据</p>
                <p className="text-xs mt-2">请确保订单管理中有订单数据</p>
              </div>
            </div>
          )}
        </div>
        </div>

        {/* 数据对比分析 */}
        {comparisonData.length > 0 && (
        <div className="bg-white rounded-lg shadow-sm border border-gray-100 p-6">
          <DataComparison 
            title="销售数据对比分析" 
            data={comparisonData} 
          />
        </div>
        )}

      {/* 订单详情模态框 */}
      <OrderDetailModal
        isOpen={showOrderModal}
        onClose={() => setShowOrderModal(false)}
        orders={convertOrdersToModalFormat(getFilteredOrdersByStatus(selectedOrderStatus))}
        title={orderModalTitle}
        showStatusFilter={false}
        totalOrders={getFilteredOrdersByStatus(selectedOrderStatus).length}
        refreshData={fetchSalesData}
      />

      {/* 详细数据表格 */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-100 p-6">
        <div className="mb-6">
          <h3 className="text-lg font-bold text-gray-800 mb-1">销售趋势明细</h3>
          <p className="text-xs text-gray-500">每日销售数据详情</p>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="bg-gray-50">
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">日期</th>
                <th className="px-4 py-3 text-right text-xs font-semibold text-gray-600 uppercase tracking-wider">销售额</th>
                <th className="px-4 py-3 text-right text-xs font-semibold text-gray-600 uppercase tracking-wider">订单数</th>
                <th className="px-4 py-3 text-right text-xs font-semibold text-gray-600 uppercase tracking-wider">客单价</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {salesTrendData.map((item, index) => {
                const avgValue = item.orders > 0 ? item.sales / item.orders : 0;
                return (
                  <tr key={index} className="hover:bg-gray-50 transition-colors">
                    <td className="px-4 py-3 text-sm text-gray-900">{item.date}</td>
                    <td className="px-4 py-3 text-sm text-right font-medium text-gray-900">
                      ¥{item.sales.toLocaleString()}
                    </td>
                    <td className="px-4 py-3 text-sm text-right text-gray-700">
                      {item.orders.toLocaleString()}
                    </td>
                    <td className="px-4 py-3 text-sm text-right text-gray-700">
                      ¥{avgValue.toFixed(2)}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  )
}
export default SalesStats

